﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;
using siof = System.IO.File;
using Ini;
using MediaInfoLib;
using System.Globalization;
using System.Resources;
using System.Reflection;
using Etier.IconHelper;
using System.Windows.Forms;

namespace Convert1
{
    
     

    public partial class Form1 : Form
    {
        private ImageList _smallImageList = new ImageList();
        private ImageList _largeImageList = new ImageList();
        private IconListManager _iconListManager;

        //Config file path
        IniFile ini = new IniFile(Environment.CurrentDirectory + "\\ffmpegguiConf.ini");
        string temp = Path.GetTempPath();
        string windir = Environment.GetEnvironmentVariable("WINDIR");
        string programfiles = Environment.GetEnvironmentVariable("PROGRAMFILES");
        string allusers = Environment.GetEnvironmentVariable("USERPROFILE");
        string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        
        public Form1()
        {
            InitializeComponent();

            _smallImageList.ColorDepth = ColorDepth.Depth32Bit;
            _largeImageList.ColorDepth = ColorDepth.Depth32Bit;

            _smallImageList.ImageSize = new System.Drawing.Size(16, 16);
            _largeImageList.ImageSize = new System.Drawing.Size(32, 32);

            _iconListManager = new IconListManager(_smallImageList, _largeImageList);

            listView1.SmallImageList = _smallImageList;
            listView1.LargeImageList = _largeImageList;

            button6.TabStop = false;
            button6.FlatStyle = FlatStyle.Flat;
            button6.FlatAppearance.BorderSize = 0;
            button6.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //Transparent
            button7.TabStop = false;
            button7.FlatStyle = FlatStyle.Flat;
            button7.FlatAppearance.BorderSize = 0;
            button7.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //Transparent
            button8.TabStop = false;
            button8.FlatStyle = FlatStyle.Flat;
            button8.FlatAppearance.BorderSize = 0;
            button8.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //Transparent

            if (ini.IniReadValue("Settings", "Color") == "Black")
                Theme.ThemeColor = RibbonTheme.Black;
            else if (ini.IniReadValue("Settings", "Color") == "Green")
                Theme.ThemeColor = RibbonTheme.Green;
            else if (ini.IniReadValue("Settings", "Color") == "Purpule")
                Theme.ThemeColor = RibbonTheme.Purple;
            else if (ini.IniReadValue("Settings", "Color") == "JellyBelly")
                Theme.ThemeColor = RibbonTheme.JellyBelly;
            else if (ini.IniReadValue("Settings", "Color") == "Halloween")
                Theme.ThemeColor = RibbonTheme.Halloween;
            else
                Theme.ThemeColor = RibbonTheme.Normal;
            this.Refresh();

            if (ini.IniReadValue("Settings", "DestinationPath") != null)
            {
                textBox1.Text = ini.IniReadValue("Settings", "DestinationPath");
            }

            try
            {
                dataSet1.ReadXml("codecs.xml");
                if (dataSet1.Tables != null)
                {
                    ribbonComboBox1.DropDownItems.Clear();
                    for (int i = 0; i < dataSet1.Tables[0].Rows.Count; i++)
                    {
                        DataRow rw = dataSet1.Tables[0].Rows[i];
                        RibbonButton rb = new RibbonButton();
                        rb.Text = rw[0].ToString();
                        rb.Value = rw[1].ToString();
                        ribbonComboBox1.DropDownItems.Add(rb);
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }

            //Preloads
            ribbonComboBox1.SelectedItem = h264Bt;
            ribbonComboBox2.SelectedItem = mp3codecsBt;
            ribbonComboBox3.SelectedItem = audio128Bt;
            ribbonComboBox5.SelectedItem = audio44100Bt;
            ribbonComboBox7.SelectedItem = stereoBt;
            ribbonComboBox6.SelectedItem = screenoriginalBt;
            ribbonComboBox4.SelectedItem = onBt;
            ribbonComboBox8.SelectedItem = aviBt;
        }

        
        private void ribbonOrbMenuItem1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Video files|*.avi;*.mkv;*.mp4;*.mpg;*.3g2;*.3gp;*.mov;*.vob;*.flv;*.mpeg;*.mjpeg;*.wmv;*.dav|Audio files|*.mp3;*.m4a;*.wma;*.wav;*.ogg;*.ac3;*.mp2|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                // Read the files
                foreach (String file in openFileDialog1.FileNames)
                {
                    try
                    {
                        string[] sizes = { "B", "KB", "MB", "GB" };
                        double len = new FileInfo(file).Length;
                        int order = 0;
                        while (len >= 1024 && order + 1 < sizes.Length)
                        {
                            order++;
                            len = len / 1024;
                        }
                        string result = String.Format("{0:0.##} {1}", len, sizes[order]);

                        string fileName = Path.GetFullPath(file);
                        string fileExt = Path.GetExtension(file);
                        MediaInfo MediaInfoLib = new MediaInfo();
                        MediaInfoLib.Open(Path.GetFullPath(file));
                        string durationinfo = MediaInfoLib.Get(StreamKind.General, 0, "Duration/String3");
                        if (durationinfo == "")
                        {
                            durationinfo = "N/A";
                        }

                        string[] row = { fileName, fileExt.TrimStart('.'), result,durationinfo };
                        var listViewItem = new ListViewItem(row, _iconListManager.AddFileIcon(file));
                        listView1.Items.Add(listViewItem);

                        if (listView1.Items[0].SubItems[1].Text == "mp3" || listView1.Items[0].SubItems[1].Text == "m4a" || listView1.Items[0].SubItems[1].Text == "ogg" || listView1.Items[0].SubItems[1].Text == "flac" || listView1.Items[0].SubItems[1].Text == "wma" || listView1.Items[0].SubItems[1].Text == "aac" || listView1.Items[0].SubItems[1].Text == "ra")
                        {
                            onlyaudioCb.Checked = true;
                            if (onlyaudioCb.Checked == true)
                            {
                                disable_video = "";
                                VCodec = "";
                                SizeString = "";
                                VBitrate = "";
                                videoaspect = "";
                                videodisabledCb.Checked = true;
                                ribbonComboBox1.Enabled = false;
                                ribbonComboBox6.Enabled = false;
                                ribbonUpDown1.Enabled = false;
                                for (int j = 0; j < 18; j++)
                                {
                                    ribbonComboBox8.DropDownItems.ElementAt(j).Visible = false;
                                }
                                ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(19);
                            }
                            else
                            {
                                videodisabledCb.Checked = false;
                                for (int j = 0; j < 18; j++)
                                {
                                    ribbonComboBox8.DropDownItems.ElementAt(j).Visible = true;
                                }
                                ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(0);
                                ribbonComboBox1.Enabled = true;
                                ribbonComboBox6.Enabled = true;
                                ribbonUpDown1.Enabled = true;
                            }
                        }

                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show("Not open a file(s)!" + ex.Message);
                    }
                }
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                textBox1.Text = folderBrowserDialog1.SelectedPath.ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Directory.CreateDirectory(temp + "\\ffconvert-tmp");
            VCodec = ribbonComboBox1.SelectedValue.ToString();
            ACodec = ribbonComboBox2.SelectedValue.ToString();
            SizeString = ribbonComboBox6.SelectedValue.ToString();
            VBitrate = "-b:v " + ribbonUpDown1.TextBoxText.ToString() + "k ";
            ABitrate = ribbonComboBox3.SelectedValue.ToString();
            Asample = ribbonComboBox5.SelectedValue.ToString();
            AChannels = ribbonComboBox7.SelectedValue.ToString();
            Avol = "-vol " + ribbonUpDown4.TextBoxText.ToString() + " ";
            if (ribbonComboBox9.TextBoxText != "None")
            {
                colorspace = "-pix_fmt " + ribbonComboBox9.TextBoxText.ToString() + " ";
                
            }

            if (ribbonComboBox10.TextBoxText != "Original")
            {
                fps = "-r " + ribbonComboBox10.SelectedValue.ToString() + " ";
            }
            else
            {
                fps = "";
            }

            Extension = ribbonComboBox8.SelectedItem.Value.ToString();
            //video disabled
            if (videodisabledCb.Checked == true)
            {
                disable_video = "-vn ";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
            }
            //IDv3
            if (idv3Cb.Checked == true)
            {
                idv3 = "-id3v2_version 3 -write_id3v1 1 ";
            }
            if (idv3Cb.Checked == false)
            {
                idv3 = "";
            }
            //Album cover
            if (coverpathTb.TextBoxText != "")
            {
                cover = "-i " + coverpathTb.TextBoxText + " -map 0:0 -map 1:0 ";
            }
            else
            {
                cover = "";
            }

            //Only Audio
            if (onlyaudioCb.Checked == true)
            {
                disable_video = "";
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
                videodisabledCb.Checked = true;
            }
            //audio disabled
            if (audiodisabledCb.Checked == false)
            {
                disable_audio = "";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
            }
            if (originalcodecsCb.Checked == true)
            {
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
                copycodecs = "-c:v copy ";
            }

            if (checkBox1.Checked == true)
            {
                hwacc = "-strict experimental ";
            }
            if (checkBox1.Checked == false)
            {
                hwacc = "";
            }

            startPoz = StartPozTb.TextBoxText;
            endPoz = EndPozTb.TextBoxText;

            //video disabled
            if (videodisabledCb.Checked == false)
            {
                disable_video = "";
                VCodec = "-c:v " + ribbonComboBox1.SelectedValue.ToString();
            }
            //audio disabled
            if (audiodisabledCb.Checked == true)
            {
                disable_audio = "-an ";
                VCodec = "-c:v " + ribbonComboBox1.SelectedValue.ToString();
                ACodec = "";
                ABitrate = "";
                Asample = "";
                AChannels = "";
                Avol = "";
            }

            string disable_sub = ribbonComboBox4.SelectedValue.ToString();
           
            if (originalcodecsCb.Checked == false)
            {
                copycodecs = "";
                //VCodec = "-vcodec " + ribbonComboBox1.SelectedValue.ToString();
            }
            //titles
            if (ribbonTextBox2.TextBoxText != "")
            {
                title = "-metadata title=" + "\"" + ribbonTextBox2.TextBoxText + "\" ";
            }
            if (ribbonTextBox3.TextBoxText != "")
            {
                author = "-metadata author=" + "\"" + ribbonTextBox3.TextBoxText + "\" ";
            }
            if (ribbonTextBox4.TextBoxText != "")
            {
                comment = "-metadata comment=" + "\"" + ribbonTextBox4.TextBoxText + "\" ";
            }
            if (ribbonTextBox5.TextBoxText != "")
            {
                album = "-metadata album=" + "\"" + ribbonTextBox5.TextBoxText + "\" ";
            }
            if (ribbonTextBox6.TextBoxText != "")
            {
                composer = "-metadata composer=" + "\"" + ribbonTextBox6.TextBoxText + "\" ";
            }
            if (ribbonTextBox7.TextBoxText != "")
            {
                year = "-metadata year=" + "\"" + ribbonTextBox7.TextBoxText + "\" ";
            }
            if (ribbonTextBox8.TextBoxText != "")
            {
                track = "-metadata track=" + "\"" + ribbonTextBox8.TextBoxText + "\" ";
            }
            if (ribbonTextBox9.TextBoxText != "")
            {
                description = "-metadata description=" + "\"" + ribbonTextBox9.TextBoxText + "\" ";
            }

            try
            {
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    listView1.Items[0].Selected = true;
                    listView1.Select();
                    
                }
                string fileName = Path.GetFileName(listView1.SelectedItems.ToString());
                string fileFull = listView1.Items[0].Text;
                string simpleFileName = Path.GetFileNameWithoutExtension(listView1.Items[0].Text);
                //Informations...
                Process ffprobeProcess = new Process();
                ffprobeProcess.StartInfo.FileName = "cmd.exe";
                ffprobeProcess.StartInfo.WorkingDirectory = System.Environment.CurrentDirectory;
                ffprobeProcess.StartInfo.Arguments = "/C Codecs\\ffprobe.exe -show_streams -i \"" + fileFull + "\"" + " 2>" + "\"" + temp + "\\ffconvert-tmp\\info.txt" + "\"";
                
                ffprobeProcess.StartInfo.CreateNoWindow = true;
                ffprobeProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                
                ffprobeProcess.Start();
                ffprobeProcess.WaitForExit();

                foreach (string duration in System.IO.File.ReadAllLines(temp + @"\ffconvert-tmp\info.txt"))
                {
                    if (duration.Contains("Duration:"))
                    {
                        string pat = @"\: ([^,]*)";
                        Regex r = new Regex(pat, RegexOptions.IgnoreCase);
                        Match m = r.Match(duration);
                        //Time split
                        string duration2 = m.ToString();
                        char[] arr = new char[] { ':', ' ' };
                        duration2 = duration2.TrimStart(arr);
                        string s2 = Regex.Replace(duration2, ".\\d{2}$", "");
                        textBox3.Text = s2;
                        var values = Regex.Split(s2, @"[\s,:]+");
                        if (s2 != "N/A")
                        {
                            int ora = int.Parse(values[0]);
                            int perc = int.Parse(values[1]);
                            int mp = int.Parse(values[2]);
                            int osszeg = ora * 3600 + 60 * perc + mp;
                            progressBar1.Maximum = osszeg;
                        }
                        //Unknown duration time
                        else
                        {
                            progressBar1.Style = ProgressBarStyle.Marquee;
                            progressBar1.MarqueeAnimationSpeed = 50;
                            var prog = Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance;
                            prog.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Indeterminate);
                           
                            label4.Text = "N/A";
                        }

                    }
                }


                
                //FFMpeg Converter starting...
                Process myProcess = new Process();
                myProcess.StartInfo.FileName = "cmd.exe";
                myProcess.StartInfo.WorkingDirectory = System.Environment.CurrentDirectory;
                myProcess.StartInfo.Arguments = "/C Codecs\\ffmpeg.exe -i \"" + fileFull + "\" " +"-y " + cover + hwacc+ startPoz + endPoz + copycodecs + VCodec + SizeString + fps + colorspace + VBitrate + videoaspect + disable_audio + ACodec + ABitrate + Asample + AChannels + Avol + disable_video + disable_sub + composer + title + author + comment + album + idv3 + "\"" + textBox1.Text + "\\" + simpleFileName + Extension + "\"" + " 2>" + "\"" + temp + "\\ffconvert-tmp\\out.txt" + "\"";
                if (checkBox2.Checked == true)
                {
                    myProcess.StartInfo.CreateNoWindow = true;
                    myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                }
                myProcess.EnableRaisingEvents = true;
                myProcess.Exited += new EventHandler(myProcess_Exited);
                myProcess.Start();

                progressBar1.Visible = true;
                progressBar1.Show();
                timer1.Enabled = true;
               
            }
            catch
            {
                MessageBox.Show("Not add source file(s)!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }
            void myProcess_Exited(object sender, EventArgs e)
            {
                this.Invoke((MethodInvoker)delegate
                {

                    if (listView1.Items.Count > 0)
                    {
                        listView1.Items.RemoveAt(0);
                    }
                    if (listView1.Items.Count > 0)
                    {
                        button1.PerformClick();
                    }
                    else
                    {
                        timer1.Stop();
                        progressBar1.Style = ProgressBarStyle.Blocks;
                        progressBar1.Minimum = 0;
                        progressBar1.Maximum = 100;
                        progressBar1.Increment(100);
                        var prog = Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance;
                        prog.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal);
                        prog.SetProgressValue(progressBar1.Value, progressBar1.Maximum);
                        label4.Text = "100%";
                        MessageBox.Show("Encoding Finished!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        coverpathTb.TextBoxText = "";
                        this.ribbonButton100.Image = global::FFMpegConverter.Properties.Resources.cover;
                        Directory.Delete(temp + "\\ffconvert-tmp",true);

                        
                    }
                });
            }

        private void ribbonUpDown1_DownButtonClicked(object sender, MouseEventArgs e)
        {
            int i = int.Parse(ribbonUpDown1.TextBoxText);
            i--;
            ribbonUpDown1.TextBoxText = i.ToString();
        }

        private void ribbonUpDown1_UpButtonClicked(object sender, MouseEventArgs e)
        {
            int i = int.Parse(ribbonUpDown1.TextBoxText);
            i++;
            ribbonUpDown1.TextBoxText = i.ToString();
        }

        private void ribbonUpDown1_TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void ribbonUpDown4_DownButtonClicked(object sender, MouseEventArgs e)
        {
            int i = int.Parse(ribbonUpDown4.TextBoxText);
            i--;
            ribbonUpDown4.TextBoxText = i.ToString();
        }

        private void ribbonUpDown4_UpButtonClicked(object sender, MouseEventArgs e)
        {
            int i = int.Parse(ribbonUpDown4.TextBoxText);
            i++;
            ribbonUpDown4.TextBoxText = i.ToString();
        }

        private void ribbonUpDown4_TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.'
                && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

        private void ribbonButton1_Click(object sender, EventArgs e)
        {
            videoaspect = "-aspect 16:9 ";
            asceptwBt.Checked = true;
            asceptsBt.Checked = false;
        }

        private void ribbonButton2_Click(object sender, EventArgs e)
        {
            videoaspect = "-aspect 4:3 ";
            asceptwBt.Checked = false;
            asceptsBt.Checked = true;
        }

        private void ribbonButton1_DoubleClick(object sender, EventArgs e)
        {
            asceptwBt.Checked = false;
            videoaspect = "";
        }

        private void ribbonButton2_DoubleClick(object sender, EventArgs e)
        {
            asceptsBt.Checked = false;
            videoaspect = "";
        }

        private void ribbonOrbMenuItem3_Click(object sender, EventArgs e)
        {
            
            settings frmK = new settings();
            frmK.tabControl1.SelectedIndex = 0;
            frmK.ShowDialog();
        }

        private void ribbonOrbMenuItem2_Click(object sender, EventArgs e)
        {
            VCodec = ribbonComboBox1.SelectedValue.ToString();
            ACodec = ribbonComboBox2.SelectedValue.ToString();
            SizeString = ribbonComboBox6.SelectedValue.ToString();
            VBitrate = "-b:v " + ribbonUpDown1.TextBoxText.ToString() + "k ";
            ABitrate = ribbonComboBox3.SelectedValue.ToString();
            Asample = ribbonComboBox5.SelectedValue.ToString();
            AChannels = ribbonComboBox7.SelectedValue.ToString();
            Avol = "-vol " + ribbonUpDown4.TextBoxText.ToString() + " ";
            string disable_sub = ribbonComboBox4.SelectedValue.ToString();
            //video disabled
            if (videodisabledCb.Checked == true)
            {
                disable_video = "-vn ";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
            }
            if (videodisabledCb.Checked == false)
            {
                disable_video = "";
                VCodec = "-vcodec " + ribbonComboBox1.SelectedValue.ToString();
            }
            //audio disabled
            if (audiodisabledCb.Checked == true)
            {
                disable_audio = "-an ";
                VCodec = "-vcodec " + ribbonComboBox1.SelectedValue.ToString();
                ACodec = "";
                ABitrate = "";
                Asample = "";
                AChannels = "";
                Avol = "";
            }
            if (audiodisabledCb.Checked == false)
            {
                disable_audio = "";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
            }
            //copy videocodecs
            if (originalcodecsCb.Checked == true)
            {
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
                copycodecs = "-c:v copy ";
            }
            if (originalcodecsCb.Checked == false)
            {
                copycodecs = "";
            }
            


        }


        private void ribbonCheckBox4_CheckBoxCheckChanged(object sender, EventArgs e)
        {
            if (labelCb.Checked == true)
            {
                ribbonTextBox2.Enabled = true;
                ribbonTextBox3.Enabled = true;
                ribbonTextBox4.Enabled = true;
                ribbonTextBox5.Enabled = true;
                ribbonTextBox6.Enabled = true;
                ribbonTextBox7.Enabled = true;
                ribbonTextBox8.Enabled = true;
                ribbonTextBox9.Enabled = true;
            }
            if (labelCb.Checked == false)
            {
                ribbonTextBox2.Enabled = false;
                ribbonTextBox3.Enabled = false;
                ribbonTextBox4.Enabled = false;
                ribbonTextBox5.Enabled = false;
                ribbonTextBox6.Enabled = false;
                ribbonTextBox7.Enabled = false;
                ribbonTextBox8.Enabled = false;
                ribbonTextBox9.Enabled = false;
            }

        }

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            for (i = 0; i < s.Length; i++)
                listView1.Items.Add(s[i]);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (textBox1.Text == "")
            {
                
            }
            else
            {
                ini.IniWriteValue("Settings", "DestinationPath", textBox1.Text);
            }
        }

        private void ribbonComboBox1_DropDownItemClicked(object sender, RibbonItemEventArgs e)
        {
            VCodec = ribbonComboBox1.SelectedValue.ToString();
            //video disabled
            if (videodisabledCb.Checked == false)
            {
                disable_video = "";
                VCodec = "-vcodec " + ribbonComboBox1.SelectedValue.ToString();
            }
            //audio disabled
            if (audiodisabledCb.Checked == true)
            {
                disable_audio = "-an ";
                VCodec = "-vcodec " + ribbonComboBox1.SelectedValue.ToString();
                ACodec = "";
                ABitrate = "";
                Asample = "";
                AChannels = "";
                Avol = "";
            }

        }

        private void ribbonComboBox2_DropDownItemClicked(object sender, RibbonItemEventArgs e)
        {
            ACodec = ribbonComboBox2.SelectedValue.ToString();
            //video disabled
            if (videodisabledCb.Checked == true)
            {
                disable_video = "-vn ";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
            }
            //audio disabled
            if (audiodisabledCb.Checked == false)
            {
                disable_audio = "";
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
            }
            if (originalcodecsCb.Checked == true)
            {
                ACodec = "-acodec " + ribbonComboBox2.SelectedValue.ToString();
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
                copycodecs = "-c:v copy ";
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            System.IO.File.Copy(temp + "ffconvert-tmp\\out.txt", temp + "ffconvert-tmp\\file-new.txt", true);
            String last = System.IO.File.ReadAllLines(temp + "ffconvert-tmp\\file-new.txt").Last();
            textBox2.Text = last;

            if (last.Contains("time="))
            {
                string pat = @"\d{2}:\d{2}:\d{2}";
                Regex r = new Regex(pat, RegexOptions.IgnoreCase);
                Match m = r.Match(last);
                string last2 = m.ToString();
                //Progressbar
                if (progressBar1.Style != ProgressBarStyle.Marquee)
                {
                    char[] arr = new char[] { ':', ' ' };
                    last2 = last2.TrimStart(arr);
                    var values = Regex.Split(last2, @"[\s,:]+");
                    int ora = int.Parse(values[0]);
                    int perc = int.Parse(values[1]);
                    int mp = int.Parse(values[2]);
                    int osszeg2 = ora * 3600 + 60 * perc + mp;
                    progressBar1.Value = osszeg2;
                    var prog = Microsoft.WindowsAPICodePack.Taskbar.TaskbarManager.Instance;
                    prog.SetProgressState(Microsoft.WindowsAPICodePack.Taskbar.TaskbarProgressBarState.Normal);
                    prog.SetProgressValue(progressBar1.Value, progressBar1.Maximum);
                    //Percent
                    int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
                    label4.Text = percent.ToString() + "%";
                }
                else
                {
                    label4.Text = "N/A";
                }

            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            Process[] prs = Process.GetProcesses();


            foreach (Process pr in prs)
            {
                if (pr.ProcessName == "ffmpeg")
                {

                    pr.Kill();
                    listView1.Items.Clear();
                    MessageBox.Show("Encoding aborted from user!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

            }
        }

        private void ribbonCheckBox6_CheckBoxCheckChanged(object sender, EventArgs e)
        {
            if (onlyaudioCb.Checked == true)
            {
                disable_video = "";
                VCodec = "";
                SizeString = "";
                VBitrate = "";
                videoaspect = "";
                videodisabledCb.Checked = true;
                ribbonComboBox1.Enabled = false;
                ribbonComboBox6.Enabled = false;
                ribbonComboBox9.Enabled = false;
                ribbonComboBox10.Enabled = false;
                ribbonUpDown1.Enabled = false;
                for (int i = 0; i < 18; i++)
                {
                    ribbonComboBox8.DropDownItems.ElementAt(i).Visible = false;
                }
                ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(19);
            }
            else
            {
                videodisabledCb.Checked = false;
                for (int i = 0; i < 18; i++)
                {
                    ribbonComboBox8.DropDownItems.ElementAt(i).Visible = true;
                }
                ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(0);
                ribbonComboBox1.Enabled = true;
                ribbonComboBox6.Enabled = true;
                ribbonComboBox9.Enabled = true;
                ribbonComboBox10.Enabled = true;
                ribbonUpDown1.Enabled = true;
            }
        }

        private void ribbonButton91_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(10);
        }

        private void ribbonButton89_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(0);
        }

        private void ribbonButton90_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(14);
        }

        private void ribbonButton80_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(6);
        }

        private void ribbonButton92_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(5);
        }

        private void ribbonButton93_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(7);
        }

        private void ribbonButton96_Click(object sender, EventArgs e)
        {
            ribbonComboBox2.SelectedItem = ribbonComboBox2.DropDownItems.ElementAt(16);
        }




        private void button6_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selected = listView1.SelectedItems[0];
                int indx = selected.Index;
                int totl = listView1.Items.Count;

                if (indx == 0)
                {
                    listView1.Items.Remove(selected);
                    listView1.Items.Insert(totl - 1, selected);
                }
                else
                {
                    listView1.Items.Remove(selected);
                    listView1.Items.Insert(indx - 1, selected);
                }
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem selected = listView1.SelectedItems[0];
                int indx = selected.Index;
                int totl = listView1.Items.Count;

                if (indx == totl - 1)
                {
                    listView1.Items.Remove(selected);
                    listView1.Items.Insert(0, selected);
                }
                else
                {
                    listView1.Items.Remove(selected);
                    listView1.Items.Insert(indx + 1, selected);
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            for (int i = listView1.SelectedIndices.Count - 1; i >= 0; i--)
            {
                listView1.Items.RemoveAt(listView1.SelectedIndices[i]);
            }
        }
        //picture resize
        public static Image resizeImage(Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }

        private void ribbonButton100_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Pictures|*.png;*.jpg;*.jpeg;*.bmp;*.gif|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                coverpathTb.TextBoxText = openFileDialog1.FileName;
                Bitmap objBitmap = new Bitmap(System.Drawing.Image.FromFile(openFileDialog1.FileName), new Size(56, 56));
                ribbonButton100.Image = objBitmap;
            }
        }

        private void listView1_DragDrop(object sender, DragEventArgs e)
        {

            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            int i;
            for (i = 0; i < s.Length; i++)
            {

                string[] sizes = { "B", "KB", "MB", "GB" };
                double len = new FileInfo(Path.GetFullPath(s[i])).Length;
                int order = 0;
                while (len >= 1024 && order + 1 < sizes.Length)
                {
                    order++;
                    len = len / 1024;
                }
                string result = String.Format("{0:0.##} {1}", len, sizes[order]);

                string fileName = Path.GetFullPath(s[i]);
                string fileExt = Path.GetExtension(s[i]);
                MediaInfo MediaInfoLib = new MediaInfo();
                MediaInfoLib.Open(Path.GetFullPath(s[i]));
                string durationinfo = MediaInfoLib.Get(StreamKind.General, 0, "Duration/String3");
                if (durationinfo=="")
                {
                    durationinfo = "N/A";
                }
                string[] row = { fileName, fileExt.TrimStart('.'), result,durationinfo };
                var listViewItem = new ListViewItem(row, _iconListManager.AddFileIcon(s[i]));
                listView1.Items.Add(listViewItem);
                if (listView1.Items[0].SubItems[1].Text == "mp3" || listView1.Items[0].SubItems[1].Text == "m4a" || listView1.Items[0].SubItems[1].Text == "ogg" || listView1.Items[0].SubItems[1].Text == "flac" || listView1.Items[0].SubItems[1].Text == "wma" || listView1.Items[0].SubItems[1].Text == "aac" || listView1.Items[0].SubItems[1].Text == "ra")
                {
                    onlyaudioCb.Checked = true;
                    if (onlyaudioCb.Checked == true)
                    {
                        disable_video = "";
                        VCodec = "";
                        SizeString = "";
                        VBitrate = "";
                        videoaspect = "";
                        videodisabledCb.Checked = true;
                        ribbonComboBox1.Enabled = false;
                        ribbonComboBox6.Enabled = false;
                        ribbonUpDown1.Enabled = false;
                        for (int j = 0; j < 18; j++)
                        {
                            ribbonComboBox8.DropDownItems.ElementAt(j).Visible = false;
                        }
                        ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(19);
                    }
                    else
                    {
                        videodisabledCb.Checked = false;
                        for (int j = 0; j < 18; j++)
                        {
                            ribbonComboBox8.DropDownItems.ElementAt(j).Visible = true;
                        }
                        ribbonComboBox8.SelectedItem = ribbonComboBox8.DropDownItems.ElementAt(0);
                        ribbonComboBox1.Enabled = true;
                        ribbonComboBox6.Enabled = true;
                        ribbonUpDown1.Enabled = true;
                    }
                }
            }
        }

        private void listView1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.All;
            else
                e.Effect = DragDropEffects.None;
        }

        private void ribbonOrbMenuItem5_Click(object sender, EventArgs e)
        {
            settings frmK = new settings();
            frmK.tabControl1.SelectedIndex = 1;
            frmK.ShowDialog();
        }


 

        

    }
}
